<template>
  <div class="cart">
    <van-nav-bar title="购物车" fixed />
    <!-- 购物车开头 -->
    <div class="cart-box" v-if="isLogin && cartList.length > 0">
      <div class="cart-title">
        <span class="all">共<i>{{ cartTotal || 0 }}</i>件商品</span>
        <span class="edit" @click="isEdit = !isEdit">
          <van-icon name="edit" />
          编辑
        </span>
      </div>

      <!-- 购物车列表 -->
      <div class="cart-list">
        <div class="cart-item" v-for="(item, index) in cartList" :key="index">
          <div class="dish" v-if="item.item.dishBasicDto !== null">
            <van-checkbox icon-size="18" :value="item.isChecked"
              @click.prevent.stop="toggleCheck(item.item.id)"></van-checkbox>
            <div class="show" @click="goDishDetail(item.item.dishBasicDto)">
              <img :src="item.item.dishBasicDto.image" alt="">
            </div>
            <div class="info" @click="goDishDetail(item.item.dishBasicDto)">
              <span class="tit text-ellipsis-2">{{ item.item.dishBasicDto.dishName }}&nbsp;&nbsp;{{
                item.item.dishBasicDto.description }}</span>
              <span class="tit text-ellipsis-2" style="font-size: 12px;">{{ item.item.flavorString }} </span>
              <span class="bottom">
                <div class="price">¥ <span>{{ item.item.totalMoney }}</span></div>
                <CountBox :value="item.item.num" @input="value => changeCount(item.item.id, value)"></CountBox>
              </span>
            </div>
          </div>
          <div class="setmeal" v-if="item.item.setmealBasicDto !== null">
            <van-checkbox icon-size="18" :value="item.isChecked"
              @click.prevent.stop="toggleCheck(item.item.id)"></van-checkbox>
            <div class="show" @click="goSetmealDetail(item.item.setmealBasicDto)">
              <img :src="item.item.setmealBasicDto.image" alt="">
            </div>
            <div class="info" @click="goSetmealDetail(item.item.setmealBasicDto)">
              <span class="tit text-ellipsis-2">{{ item.item.setmealBasicDto.dishName }}&nbsp;&nbsp;{{
                item.item.setmealBasicDto.description }} </span>
              <span class="bottom">
                <div class="price">¥ <span>{{ item.item.totalMoney }}</span></div>
                <CountBox :value="item.item.num" @input="value => changeCount(item.item.id, value)"></CountBox>
              </span>
            </div>
          </div>
        </div>
      </div>
      <div class="footer-fixed">
      <div class="all-check" @click="toggleAllCheck">
        <van-checkbox :value="isAllChecked" icon-size="18"></van-checkbox>
        全选
      </div>
      <div class="all-total">
        <div class="price" v-if="!isEdit">
          <span>合计：</span>
          <span>¥ <i class="totalPrice">{{ selPrice }}</i></span>
        </div>
        <div v-if="!isEdit" :class="{ disabled: selCount === 0 }" class="goPay" @click="goPay">
          去结算（{{ selCount }}）
        </div>
        <div v-else :class="{ disabled: selCount === 0 }" @click="handleDel" class="delete">
          删除({{ selCount }})
        </div>
      </div>
    </div>
    </div>
    <div class="empty-cart" v-else>
      <img src="@/assets/cart/empty.png" alt="">
      <div class="tips">
        您的购物车是空的, 快去逛逛吧
      </div>
      <div class="btn" @click="$router.push('/')">去逛逛</div>
    </div>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import { mapState, mapGetters } from 'vuex'
import CountBox from '@/components/CountBox.vue'

export default {
  name: 'CartIndex',
  // import引入的组件需要注入到对象中才能使用
  components: {
    CountBox
  },
  data () {
  // 这里存放数据
    return {
      isEdit: false
    }
  },
  // 监听属性 类似于data概念
  computed: {
    isLogin () {
      return this.$store.getters.token
    },
    ...mapState('cart', ['cartList']),
    ...mapGetters('cart', ['cartTotal', 'selCount', 'selPrice', 'isAllChecked'])
  },
  // 监控data中的数据变化
  watch: {
    cartList: {
      deep: true,
      immediate: true,
      handler (cartList) {
        cartList = cartList.forEach(item => {
          if (item.item.dishBasicDto !== null) {
            item.item.dishBasicDto.image = item.item.dishBasicDto.image.split(',')[0]
          }
          if (item.item.setmealBasicDto !== null) {
            item.item.setmealBasicDto.image = item.item.setmealBasicDto.image.split(',')[0]
          }
        })
      }
    },
    isEdit (value) {
      if (value) {
        this.$store.commit('cart/toggleAllCheck', false)
      } else {
        this.$store.commit('cart/toggleAllCheck', true)
      }
    }
  },
  // 方法集合
  methods: {
    toggleCheck (goodsId) {
      this.$store.commit('cart/toggleCheck', goodsId)
    },
    toggleAllCheck () {
      this.$store.commit('cart/toggleAllCheck', !this.isAllChecked)
    },
    // 跳转到菜品详情界面
    goDishDetail (dishBasicDto) {
      this.$router.push({
        name: 'DishDetail',
        params: {
          dishBasicDto
        }
      })
    },
    // 跳转到套餐详情界面
    goSetmealDetail (setmealBasicDto) {
      this.$router.push({
        name: 'SetmealDetail',
        params: {
          setmealBasicDto
        }
      })
    },
    changeCount (id, num) {
      this.$store.dispatch('cart/changeCountAction', {
        id,
        num
      })
    },
    async handleDel () {
      this.$dialog.confirm({
        title: '温馨提示',
        message: '确定要删除购物车数据吗',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      }).then(() => {
        if (this.selCount === 0) return
        this.$store.dispatch('cart/delSelect')
        this.isEdit = false
      }).catch(() => {
      })
    },
    // 去付款
    goPay () {
      let status = 0
      this.$dialog.confirm({
        title: '温馨提示',
        message: '请选择就餐方式',
        confirmButtonText: '外送到家',
        cancelButtonText: '到店取餐'
      }).then(() => {
        // 外送到家
        status = 1
        this.$router.push({
          name: 'PayIndex',
          params: {
            status
          }
        })
      }).catch(() => {
        // 到店取餐
        status = 2
        this.$router.push({
          name: 'PayIndex',
          params: {
            status
          }
        })
      })
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    if (this.isLogin) {
      this.$store.dispatch('cart/getCartAction')
    }
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang="less" scoped>
.cart {
  padding-top: 46px;
  padding-bottom: 100px;
  background-color: #f5f5f5;
  min-height: 100vh;
  .cart-title {
    height: 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    font-size: 14px;
    .all {
      i {
        font-style: normal;
        margin: 0 2px;
        color: #fa2209;
        font-size: 16px;
      }
    }
    .edit {
      .van-icon {
        font-size: 18px;
      }
    }
  }

  .cart-item {

    .dish {
      margin: 0 10px 10px 10px;
        padding: 10px;
        display: flex;
        justify-content: space-between;
        background-color: #ffffff;
        border-radius: 5px;
    }

    .setmeal {
      margin: 0 10px 10px 10px;
    padding: 10px;
    display: flex;
    justify-content: space-between;
    background-color: #ffffff;
    border-radius: 5px;
    }

    .show img {
      width: 100px;
      height: 100px;
    }
    .info {
      width: 210px;
      padding: 10px 5px;
      font-size: 14px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .bottom {
        display: flex;
        justify-content: space-between;
        .price {
          display: flex;
          align-items: flex-end;
          color: #fa2209;
          font-size: 12px;
          span {
            font-size: 16px;
          }
        }
        .count-box {
          display: flex;
          width: 110px;
          .add,
          .minus {
            width: 30px;
            height: 30px;
            outline: none;
            border: none;
          }
          .inp {
            width: 40px;
            height: 30px;
            outline: none;
            border: none;
            background-color: #efefef;
            text-align: center;
            margin: 0 5px;
          }
        }
      }
    }
  }
}

.footer-fixed {
  position: fixed;
  left: 0;
  bottom: 50px;
  height: 50px;
  width: 100%;
  border-bottom: 1px solid #ccc;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;

  .all-check {
    display: flex;
    align-items: center;
    .van-checkbox {
      margin-right: 5px;
    }
  }

  .all-total {
    display: flex;
    line-height: 36px;
    .price {
      font-size: 14px;
      margin-right: 10px;
      .totalPrice {
        color: #fa2209;
        font-size: 18px;
        font-style: normal;
      }
    }

    .goPay, .delete {
      min-width: 100px;
      height: 36px;
      line-height: 36px;
      text-align: center;
      background-color: #fa2f21;
      color: #fff;
      border-radius: 18px;
      &.disabled {
        background-color: #ff9779;
      }
    }
  }
}
.empty-cart {
  padding: 80px 30px;
  img {
    width: 140px;
    height: 92px;
    display: block;
    margin: 0 auto;
  }
  .tips {
    text-align: center;
    color: #666;
    margin: 30px;
  }
  .btn {
    width: 110px;
    height: 32px;
    line-height: 32px;
    text-align: center;
    background-color: #fa2c20;
    border-radius: 16px;
    color: #fff;
    display: block;
    margin: 0 auto;
  }
}
</style>
